package com.hst.capacity.application.biz.impl;

import com.alibaba.fastjson2.JSON;
import com.hst.capacity.application.biz.IntercityLineBiz;
import com.hst.capacity.domain.common.constants.Constants;
import com.hst.capacity.domain.exception.BusinessException;
import com.hst.capacity.domain.model.entity.driver.DriverLineBandEntity;
import com.hst.capacity.domain.model.entity.setting.line.CityLineEntity;
import com.hst.capacity.domain.model.entity.setting.line.IntercityLineAutoGrabEntity;
import com.hst.capacity.domain.model.entity.setting.line.IntercityLineEntity;
import com.hst.capacity.domain.model.entity.setting.price.IntercityPriceEntity;
import com.hst.capacity.domain.model.request.setting.line.CityLineParam;
import com.hst.capacity.domain.model.request.setting.line.IcLineSaveParam;
import com.hst.capacity.domain.model.request.setting.line.IntercityLineAutoGrabParam;
import com.hst.capacity.domain.model.request.setting.price.IcSaveParam;
import com.hst.capacity.domain.model.response.driver.DriverBandLineVO;
import com.hst.capacity.domain.model.response.setting.line.CityLineInfoVO;
import com.hst.capacity.domain.model.response.setting.line.CustomCityLineVO;
import com.hst.capacity.domain.model.response.setting.line.IntercityLineVO;
import com.hst.capacity.domain.model.response.setting.price.IntercityPriceVO;
import com.hst.capacity.domain.repository.redis.CacheRedis;
import com.hst.capacity.infra.convertor.IntercityConvertor;
import com.hst.capacity.infra.persistence.jpa.driver.DriverLineBandRepository;
import com.hst.capacity.infra.persistence.jpa.setting.line.CityLineRepository;
import com.hst.capacity.infra.persistence.jpa.setting.line.IntercityLineAutoGrabRepository;
import com.hst.capacity.infra.persistence.jpa.setting.line.IntercityLineRepository;
import com.hst.capacity.infra.persistence.jpa.setting.price.IcPriceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class IntercityLineBizImpl implements IntercityLineBiz {

    @Autowired
    IntercityLineRepository lineRepository;

    @Autowired
    CityLineRepository clRepository;

    @Autowired
    IntercityLineAutoGrabRepository autoGrabRepository;

    @Autowired
    IcPriceRepository icPriceRepository;

    @Autowired
    DriverLineBandRepository dbRepository;

    @Autowired
    CacheRedis cacheRedis;

    @Override
    public CityLineInfoVO getCityLine(String idCityLine) {
        CityLineInfoVO vo = new CityLineInfoVO(clRepository.findByIdCityLine(idCityLine));
        return vo;
    }

    @Override
    public String cityLineSave(CityLineParam param) {
        CityLineEntity entity = IntercityConvertor.INSTANCE.convert(param);
        return clRepository.save(entity).getIdCityLine();
    }

    /**
     * 获取城际线路信息
     * @param idLine
     * @return
     */
    @Override
    public IntercityLineVO getInterCityLine(String idLine) {
        return lineRepository.findByIdLine(idLine);
    }

    /**
     * 城际线路保存
     * @param param
     * @return
     */
    @Override
    public String IcLineSave(IcLineSaveParam param) {
        IntercityLineEntity entity = lineRepository.findIntercityLineEntityByIdLine(param.getIdLine());
        //创建单条线路信息
        entity = IntercityConvertor.INSTANCE.convert(param);
        return lineRepository.save(entity).getIdLine();
    }

    @Override
    public IntercityPriceVO getInterCityLinePrice(String idLine) {
        return icPriceRepository.findBbyIdLine(idLine);
    }

    @Override
    public Integer icLinePriceSave(IcSaveParam param) {
        log.info("IcSaveParam:"+JSON.toJSONString(param));
        IntercityPriceEntity entity = icPriceRepository.findByIdLine(param.getIdLine());
        log.info("IntercityPriceEntity:"+JSON.toJSONString(entity));
        Integer idIntercityLinePrice = null;
        if (entity == null) {
            entity = new IntercityPriceEntity();
        } else {
            idIntercityLinePrice = entity.getIdIntercityLinePrice();
        }
        //创建单条线路信息
        entity = IntercityConvertor.INSTANCE.convert(param);
        entity.setIdIntercityLinePrice(idIntercityLinePrice);
        return icPriceRepository.save(entity).getIdIntercityLinePrice();
    }

    /**
     * 城际线路状态更新
     * @param param
     * @return
     */
    @Override
    public boolean updateCityLineStatus(IcLineSaveParam param) {
        int updCount = clRepository.updateCityLineStatus(param.getStatus(),param.getIdCityLine());
        if (updCount>0){
            return true;
        }
        return false;
    }

    /**
     * 获取城际线路信息
     * @param cityCode
     * @return
     */
    @Override
    public HashMap getCityLines(String cityCode) {
        HashMap<String, List<IntercityLineEntity>> returns = new HashMap<>();

//        returns.put("start",lineRepository.findByStartCityCode(cityCode));
//        returns.put("end",lineRepository.findByEndCityCode(cityCode));

        //全线路数据取得
        List<CityLineEntity> lstCityLine = clRepository.findByCityCode(cityCode);
        if (lstCityLine.size() == 0) {
            returns.put("all", null);
        }
        ArrayList<IntercityLineEntity> allList = new ArrayList<>();

        for (CityLineEntity cityLine:lstCityLine){
            List<IntercityLineEntity> listStart = lineRepository.findByIdCityLineAndStartCityCode(cityCode,cityLine.getIdCityLine());
            List<IntercityLineEntity> listEnd = lineRepository.findByIdCityLineAndEndCityCode(cityCode,cityLine.getIdCityLine());
            allList.addAll(listStart);
            allList.addAll(listEnd);
        }

        returns.put("all",allList);

        return returns;
    }

    /**
     * 根据城际定制线路列表
     * @param cityCode
     * @return
     */
    @Override
    public HashMap getCustomCityLines(String cityCode) {
        HashMap<String, List<CustomCityLineVO>> returns = new HashMap<>();

        //全线路数据取得
        List<CityLineEntity> lstCityLine = clRepository.findByCityCode(cityCode);
        if (lstCityLine.size()==0){
            throw new BusinessException(4001,"没有设置相关线路");
        }
        ArrayList<CustomCityLineVO> allList = new ArrayList<>();

        for (CityLineEntity cityLine:lstCityLine){
            List<CustomCityLineVO> listStart = lineRepository.findVoByIdCityLineAndStartCityCode(cityLine.getStationRegionCode(),cityLine.getIdCityLine());
            if (listStart.size()==0){
                listStart = lineRepository.findVoByIdCityLineAndStartCityCode(cityLine.getCityCode(),cityLine.getIdCityLine());
            }
            List<CustomCityLineVO> listEnd = lineRepository.findVoByIdCityLineAndEndCityCode(cityLine.getStationRegionCode(),cityLine.getIdCityLine());
            if (listEnd.size()==0){
                listEnd = lineRepository.findVoByIdCityLineAndEndCityCode(cityLine.getCityCode(),cityLine.getIdCityLine());
            }

            allList.addAll(listStart);
            allList.addAll(listEnd);
        }
        returns.put("all",allList);

        return returns;
    }

    @Override
    public HashMap findCityLineByCode(CityLineParam param) {
        Pageable pageable = PageRequest.of(param.getPageIndex()-1,param.getPageSize(), Sort.Direction.DESC, "createTime");
        Page<CityLineInfoVO> lst = clRepository.findCityLineByCityCode(param.getCityCode(), pageable);
        for (CityLineInfoVO vo : lst.getContent()) {
            List<IntercityLineEntity> list = lineRepository.findByIdCityLine(vo.getIdCityLine());
            if (list != null)
                vo.setIcLineList(IntercityConvertor.INSTANCE.convert2VOLst(list));
        }

        HashMap<String, Object> returns = new HashMap<>();
        int size = (lst.getContent() == null) ? 0 : lst.getContent().size();
        returns.put("total", size);
        returns.put("list", lst.getContent());

        return returns;
    }

    @Override
    public IntercityLineAutoGrabEntity intercityLineAutoGrabSave(IntercityLineAutoGrabParam param) {
        log.info("IntercityLineAutoGrabParam save"+ JSON.toJSONString(param));
        IntercityLineAutoGrabEntity entity = IntercityConvertor.INSTANCE.convert(param);
        return autoGrabRepository.save(entity);
    }

    @Override
    public List<IntercityLineAutoGrabEntity> findAutoGrabListByIdLine(String idLine) {
        return autoGrabRepository.findByIdLine(idLine);
    }

    @Override
    public IntercityLineAutoGrabEntity findAutoGrabInfo(String idLineAutoGrab) {
        IntercityLineAutoGrabEntity autoGrabEntity = autoGrabRepository.findByIdLineAutoGrab(idLineAutoGrab);
        return autoGrabEntity;
    }

    @Override
    public List<IntercityLineAutoGrabEntity> findAllIntercityLineAutoGrab() {
        return autoGrabRepository.findAll();
    }

    @Override
    public HashMap getBindDriverList(String idFranchisee, String idCityLine) {
        HashMap<String, List<DriverBandLineVO>> bindingInfo = new HashMap<>();
        List<DriverBandLineVO> unBindingLst = dbRepository.findUnBandDriverListByIdCityLine(idFranchisee,idCityLine);
        bindingInfo.put("unBinding", unBindingLst);
        List<DriverBandLineVO> bindingLst = dbRepository.findBandDriverListByIdCityLine(idFranchisee,idCityLine);
        bindingInfo.put("bindingLst", bindingLst);
        return bindingInfo;
    }

    @Override
    public boolean bindDriver(String idDriverLst, String idCityLine, int bandKbn) {
        boolean ret = false;
        String[] lst = idDriverLst.split(",");
        // 0:未绑定;1：绑定
        if (Constants.BindKbn.Binding == bandKbn) {
            for (String idDriver : lst) {
                DriverLineBandEntity db = new DriverLineBandEntity();
                db.setIdDriver(idDriver);
                db.setIdCityLine(idCityLine);
                db.setCreateBy(Constants.Def_CreateBy);
                dbRepository.save(db);
            }
            ret = true;
        }else{
            for (String idDriver : lst) {
                dbRepository.deleteByIdDriverAndIdCityLine(idDriver, idCityLine);
            }
            ret = true;
        }
        return ret;
    }

    @Override
    public Integer orderGrabLimit(String idLine, int maxGrabNum) {
        cacheRedis.writeLineGrabMaxNumValue(idLine, maxGrabNum);
        return cacheRedis.getLineGrabMaxNumValue(idLine);
    }

    @Override
    public Integer findOrderGrabNum(String idLine) {
        return cacheRedis.getLineGrabMaxNumValue(idLine);
    }

}
